package com.jackstraw.jack_base.util.tenant.filter;


import com.jackstraw.jack_base.util.StringUtil;
import com.jackstraw.jack_base.util.entity.DefaultConstants;
import com.jackstraw.jack_base.util.tenant.contextholder.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter
public class TenantFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        String requestURI = httpServletRequest.getRequestURI();
        String tenantName = httpServletRequest.getHeader("tenantName");
        if (StringUtil.StringUtilsBylang3.isEmpty(tenantName)) {
            tenantName = DefaultConstants.DEFAULT_TENANT_NAME;
        }
        TenantContextHolder.set(tenantName);

        long start = System.currentTimeMillis();
        log.debug("TenantFilter开始，开始时间:[{}]----------requestURI:[{}]----------tenantName:[{}]", start, requestURI, tenantName);

        filterChain.doFilter(httpServletRequest, httpServletResponse);

        TenantContextHolder.clear();
        long end = System.currentTimeMillis();
        log.debug("TenantFilter结束，结束时间:[{}],共用时:[{}]----------requestURI:[{}]----------tenantName:[{}]", end, end - start, requestURI, tenantName);


    }
}
